package org.cwnuit.train.acton;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.cwnuit.train.domain.Trains;
import org.cwnuit.train.domain.Users;
import org.cwnuit.train.domain.Wtype;
import org.cwnuit.train.service.TrainsService;
import org.cwnuit.train.service.UsersService;
import org.cwnuit.train.service.WtypeService;
import org.cwnuit.train.utils.CreateExcel;
import org.cwnuit.train.utils.MapUtil;
import org.cwnuit.train.utils.PageModel;

@SuppressWarnings("all")
public class UsersAction extends HttpServlet{
	
	UsersService usersServices = new UsersService();
	TrainsService trainsServices = new TrainsService();
    WtypeService wtypeService = new WtypeService();
	protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String cmd = request.getParameter("cmd");
		
		if (cmd.equals("login")) {//用户登录
			Users user = userLogin(request.getParameter("uname"),request.getParameter("upass"));
			if(null!=user)
			{
				request.getSession().setAttribute("manager",user);
				int tid = user.getTid();
				Trains train = findTrain("SELECT * FROM Trains WHERE tid =" + tid);
				request.getSession().setAttribute("mtrain",train);
				if(user.getUrole()==5){
					int wid = user.getWid();
					Wtype wtype = wtypeService.findWtype("SELECT * FROM Wtype WHERE wid = " + wid );
					request.getSession().setAttribute("wtype",wtype);
				}
				response.sendRedirect("web/main.jsp");
			}else{
				request.getSession().setAttribute("msg","对不起!用户名或者密码错误,登陆失败!");
				response.sendRedirect("login.jsp");
			}
			
		} else if (cmd.equals("logout")) {//用户登出
			request.getSession().removeAttribute("manager");
			response.sendRedirect("login.jsp");
			
		} else if (cmd.equals("list")) {//分页列出信息
			request.setAttribute("pm", listUser(request));
			request.setAttribute("content_tittle", "用户列表");
			request.setAttribute("trains", findTrains("SELECT * FROM Trains"));
			request.getRequestDispatcher("web/users/list.jsp").forward(request, response);
		} else if (cmd.equals("adding")) {//添加前准备数据信息
			request.setAttribute("content_tittle", "添加新用户");
			request.setAttribute("trains", MapUtil.getTrainsMap(findTrains("SELECT * FROM Trains")));
			request.setAttribute("wtypes", findWtypes("SELECT * FROM Wtype"));
			request.getRequestDispatcher("web/users/input.jsp").forward(request, response);
		} else if(cmd.equals("update")){//修改信息
			int uid = Integer.parseInt(request.getParameter("uid"));
			request.setAttribute("user", findUser(uid));
			request.setAttribute("content_tittle", "修改用户信息");
			request.setAttribute("wtypes", findWtypes("SELECT * FROM Wtype"));
			request.setAttribute("trains", MapUtil.getTrainsMap(findTrains("SELECT * FROM Trains")));
			request.getRequestDispatcher("web/users/input.jsp").forward(request, response);
		}else if (cmd.equals("input")) {//添加或者修改
			if (request.getParameter("uid") == null||request.getParameter("uid").equals("")) {
				if (addUser(request)) {
					request.setAttribute("msg", "恭喜你，添加成功！");
					request.getRequestDispatcher("users?cmd=list").forward(
							request, response);
				}else{
					request.setAttribute("msg", "对不起！该用户名已经存在，信息添加失败！");
					request.setAttribute("trains", MapUtil.getTrainsMap(findTrains("SELECT * FROM Trains")));
					request.getRequestDispatcher("web/users/input.jsp").forward(request, response);
				}
				
			} else {
				if (updateUser(request)) {
					request.setAttribute("msg", "恭喜你，成功修改用户！");
				}else {
					request.setAttribute("msg", "对不起，用户修改未成功！");
				}
				request.getRequestDispatcher("users?cmd=list").forward(request, response);
			}
		}else if(cmd.equals("pwd")){
			if(updateUserPWD(request))
			{
				request.getSession().removeAttribute("manager");
				int uid = Integer.parseInt(request.getParameter("uid"));
				Users user = findUser(uid);
				request.getSession().setAttribute("manager",user);
				request.setAttribute("msg", "恭喜你，信息修改成功！");
			}else{
				request.setAttribute("msg", "对不起！信息修改失败！");
			}
			request.getRequestDispatcher("web/users/updatepwd.jsp").forward(
					request, response);
		} else if(cmd.equals("delete")){//删除信息
			if(deleteUser(request)){
				request.setAttribute("msg", "恭喜你，你已经成功删除了一条用户的记录！");
			} else {
				request.setAttribute("msg", "对不起，你删除记录失败！");
			}
			request.getRequestDispatcher("users?cmd=list").forward(request, response);
		}else if(cmd.equals("list_che")){//车站管理员对公共用户的管理列表
			request.setAttribute("pm", listcheUser(request));
			request.setAttribute("content_tittle", "本站用户列表");
			Users user = (Users)request.getSession().getAttribute("manager");
			request.setAttribute("trains", findTrains("SELECT * FROM Trains WHERE tid = "+user.getTid()));
			request.getRequestDispatcher("web/users/list_che.jsp").forward(request, response);
		} else if (cmd.equals("adding_che")) {//添加前准备数据信息
			request.setAttribute("content_tittle", "添加新用户");
			request.setAttribute("wtypes", findWtypes("SELECT * FROM Wtype"));
			request.getRequestDispatcher("web/users/input_che.jsp").forward(request, response);
		}else if (cmd.equals("input_che")) {//添加或者修改公共用户
			String msg = "本站用户列表";
			String link = "users?cmd=list_che";
			if (request.getParameter("uid").equals("") || request.getParameter("uid") == null) {
				if (addUser(request)) {
					request.setAttribute("msg", "恭喜你，成功添加一个用户！");
				}else{
					request.setAttribute("msg", "对不起！该用户名已经存在，信息添加失败！");
					link = "web/users/input_che.jsp";
					msg = "添加新公共用户";
				}
				
			} else {
				if (updateUser(request)) {
					request.setAttribute("msg", "恭喜你，成功修改用户！");
				}else {
					request.setAttribute("msg", "对不起，用户修改未成功！");
				}
			}
			request.setAttribute("content_tittle", msg);
			request.getRequestDispatcher(link).forward(request, response);
		} else if(cmd.equals("update_che")){//车站组修改用户信息
			int uid = Integer.parseInt(request.getParameter("uid"));
			request.setAttribute("user", findUser(uid));
			request.setAttribute("content_tittle", "用户的修改");
			request.setAttribute("wtypes", findWtypes("SELECT * FROM Wtype"));
			request.getRequestDispatcher("web/users/input_che.jsp").forward(request, response);
		}else if(cmd.equals("delete_che")){//车站组删除用户信息
			if(deleteUser(request)){
				request.setAttribute("msg", "恭喜你，你已经成功删除了一条用户的记录！");
			} else {
				request.setAttribute("msg", "对不起，你删除记录失败！");
			}
			request.setAttribute("content_tittle", "本站用户列表");
			request.getRequestDispatcher("users?cmd=list_che").forward(request, response);
		}else if (cmd.equals("search")) {//搜索用户
			request.setAttribute("pm", listmohuUser(request));
			request.setAttribute("trains", findTrains("SELECT * FROM Trains"));
			request.getRequestDispatcher("web/users/list.jsp").forward(
					request, response);
			
		}else if(cmd.equals("export")){
			findUsersToExcel(usersServices.findUsersToExcel(getAllUsers(request)),request);
			request.getRequestDispatcher("web/excel.jsp").forward(
					request, response);
		}
		
	}
	
	
	// 用户登录
	private Users userLogin(String uname,String upass) {
		return usersServices.userLogin(uname, upass);
	}
	
	// 分页查询用户信息
	private PageModel listUser(HttpServletRequest request) {
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		} catch (NumberFormatException e) {
			offset = 0;
		}
		String SQL = "SELECT * FROM users ORDER BY urole,uid DESC";
		PageModel pm = usersServices.findByPage(offset, 10, SQL);
		return pm;
	}
	
	// 查询所有车站信息
	private List<Trains> findTrains(String SQL) {
		return trainsServices.findTrains(SQL);
	}
	
	// 查询学习人员职名
	private List<Wtype> findWtypes(String SQL) {
		return wtypeService.findWtypes(SQL);
	}

	// 添加用户信息
	private boolean addUser(HttpServletRequest request) {
		String SQL = "";
		String uname = request.getParameter("uname");
		int urole = Integer.parseInt(request.getParameter("urole"));
		String upass = request.getParameter("upass");
		String uface = request.getParameter("uface");
		int tid = Integer.parseInt(request.getParameter("tid"));
		int wid = Integer.parseInt(request.getParameter("wid"));
		if(tid==0)
		{
			SQL = "INSERT INTO users(uname,upass,urole,uface,wid) VALUES('"
				+ uname + "','" + upass + "',"+urole+",'" + uface +"',"+ wid + ")";
		}else
		{
			SQL = "INSERT INTO users(uname,upass,urole,tid,uface,wid) VALUES('"
				+ uname + "','" + upass + "',"+urole+","+tid+",'" + uface +"'," + wid + ")";
		}
		int num = usersServices.findUsers("SELECT * FROM Users WHERE uname = '"+uname+"'").size();
		if(num==0)
		{
			return usersServices.addUser(SQL);
		}else{
			return false;
		}
	}
	
	// 修改用户信息
	private boolean updateUser(HttpServletRequest request) {
		int uid = Integer.parseInt(request.getParameter("uid"));
		int tid = Integer.parseInt(request.getParameter("tid"));	
		int wid = Integer.parseInt(request.getParameter("wid"));
		String uname = request.getParameter("uname");
		int urole = Integer.parseInt(request.getParameter("urole"));
		String upass = request.getParameter("upass");
		String uface = request.getParameter("uface");
		
		String SQL = "UPDATE users SET uname = '" + uname + "',upass = '"
				+ upass + "',uface = '" + uface + "',urole = "+urole+",tid = "+tid+", wid = " + wid + " WHERE uid = " + uid;
		return usersServices.updateUser(SQL);
	}

	// 查找指定用户信息
	private Users findUser(int tid) {
		String SQL = "SELECT * FROM users WHERE uid = " + tid;
		return usersServices.findUser(SQL);
	}
	
	// 用户自己修改自己信息
	private boolean updateUserPWD(HttpServletRequest request) {
		int uid = Integer.parseInt(request.getParameter("uid"));
		String upass = request.getParameter("upass");
		String uface = request.getParameter("uface");
		String uremark = request.getParameter("uremark");
		
		String SQL = "UPDATE users SET upass = '"
				+ upass + "',uface = '" + uface  + "' WHERE uid = " + uid;
		return usersServices.updateUser(SQL);
	}
	
	// 删除用户信息
	private boolean deleteUser(HttpServletRequest request) {
		int uid = Integer.parseInt(request.getParameter("uid"));
		String SQL = "DELETE FROM users WHERE uid = " + uid;
		return usersServices.deleteUser(SQL);
	}
	
	// 查询车站信息
	private Trains findTrain(String SQL) {
		return trainsServices.findTrain(SQL);
	}
	
	// 车站组分页查询用户信息
	private PageModel listcheUser(HttpServletRequest request) {
		Users user = (Users)request.getSession().getAttribute("manager");
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		} catch (NumberFormatException e) {
			offset = 0;
		}
		String SQL = "SELECT * FROM Users WHERE tid ="+user.getTid()+" AND uid!="+user.getUid()+" ORDER BY uid DESC";
		PageModel pm = usersServices.findByPage(offset, 10, SQL);
		return pm;
	}
	
	// 模糊分页查询用户信息
	private PageModel listmohuUser(HttpServletRequest request) {
		
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		} catch (NumberFormatException e) {
			offset = 0;
		}
		String SQL = "SELECT * FROM users WHERE 1=1"+condition(request)+" ORDER BY uid DESC";
		PageModel pm = usersServices.findByPage(offset, 10, SQL);
		return pm;
	}
	
	//查询条件过滤
    private String condition(HttpServletRequest request){
    	String condition = "";
    	if((request.getParameter("uname")!=null)&&(!request.getParameter("uname").equals("")))
    	{
    		condition += " AND (uname like '%"+request.getParameter("uname")+"%' OR uface like '%"+request.getParameter("uname")+"%')";
    	}
    	if((request.getParameter("tid")!=null)&&(!request.getParameter("tid").equals("0")))
    	{
    		condition += " AND tid = "+request.getParameter("tid");
    	}
    	if((request.getParameter("urole")!=null)&&(!request.getParameter("urole").equals("1000")))
    	{
    		condition += " AND urole = "+request.getParameter("urole");
    	}
    	request.setAttribute("uname", request.getParameter("uname"));
    	request.setAttribute("tid", request.getParameter("tid"));
    	request.setAttribute("urole", request.getParameter("urole"));
    	return condition;
    }
    
     // 查询所有用户信息
	private List getAllUsers(HttpServletRequest request) {		
		String SQL = "SELECT * FROM users WHERE 1=1"+condition(request)+" ORDER BY tid ASC";
		return usersServices.findUsers(SQL);
	}
	 //导出到Excel
	public String findUsersToExcel(List data,HttpServletRequest request){	
		CreateExcel ce = new CreateExcel();
		String filename = "train_data.xls";
		String path = request.getRealPath("/image");
		String file = request.getRealPath("/image/"+filename);
		ce.createExcel(path,file,data);
		return filename;
	}
}
